<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogInfo?.[dialogType]?.title"
    :width="dialogInfo?.width"
    @close="() => handleClose(false)"
  >
    <SubmitForm
      ref="submitFormRef"
      :schemas="submitFormSchema"
      :model="submitForm"
      label-width="100"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => handleClose(false)">取消</el-button>
        <el-button type="primary" @click="handleCheckFormRules(handleCommit)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { cloneDeep } from 'lodash'
import { ElMessage } from 'element-plus'
import { readLocalJsonFile } from '@/utils'
import { SubmitForm } from '@/components/SubmitForm'
import dialogHooks from '@/hooks/dialogHooks'

const emit = defineEmits<{ (e: 'close'): void }>()
const props = defineProps<{ dialogInfo?: Record<string, any>; jsonName: string }>()

const {
  dialogVisible,
  submitForm,
  submitFormRef,
  submitFormSchema,
  handleClose,
  handleCheckFormRules
} = dialogHooks(emit)

const dialogType = ref('')
const handleOpen = async (type: string, data) => {
  dialogType.value = type
  const tempData = await readLocalJsonFile(props.jsonName)
  const index = tempData.findIndex(el => el.field === 'password')
  if (type === 'edit' && index > -1) {
    tempData[index] = {
      label: '',
      field: '',
      col: 12,
      type: ''
    }
  }
  submitFormSchema.value = tempData
  submitForm.value = cloneDeep(data)
  dialogVisible.value = true
}
const handleCommit = async () => {
  const { code } = await props.dialogInfo?.[dialogType.value]?.api(submitForm.value)
  if (code === 0) {
    ElMessage.success(`${props.dialogInfo?.[dialogType.value]?.title}成功`)
    handleClose(true)
  }
}
defineExpose({ handleOpen })
</script>
